<template>
    <div>
        <h-section title="对接系统设置" collapse>
            <flexbox class="cell-item">
                <div class="font-w-b">JIRA对接：</div>
                <div class="cursor-pointer" @click="showFlowImg">提示：在此配置JIRA对接信息，可开启同步需求到jira功能</div>
            </flexbox>
            <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                <a-row>
                    <a-col :span="24">
                        <a-form-item label="需求同步到Jira">
                            <a-switch v-model:checked="form.isSyncJira" @change="handleSwitchChange" />
                        </a-form-item>
                    </a-col>
                    <!-- <a-col :span="24">
                        <a-form-item label="域名地址" name="url">
                            <a-select placeholder="请选择" v-model:value="form.url" style="width: 300px" allowClear :disabled="!form.isSyncJira" @change="handleSelectChange($event, 'url')">
                                <a-select-option :key="item.dimensionName" v-for="item of dicOptions.jiraUrl">
                                    {{ item.dimensionName }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col> -->
                    <a-col :span="24">
                        <a-form-item label="项目关键字" name="projectKey">
                            <a-select
                                placeholder="请选择"
                                v-model:value="form.projectName"
                                style="width: 300px"
                                allowClear
                                :disabled="!form.isSyncJira"
                                @change="handleSelectChange($event, 'projectName')"
                            >
                                <a-select-option :key="item.dimensionName" v-for="item of options.projectName">
                                    {{ item.dimensionName }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="模块" name="component">
                            <a-select
                                placeholder="请选择"
                                v-model:value="form.component"
                                style="width: 300px"
                                allowClear
                                :disabled="!form.isSyncJira"
                                @change="handleSelectChange($event, 'component')"
                            >
                                <a-select-option :key="item.name" v-for="item of options.component">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="看板" name="board">
                            <a-select
                                placeholder="请选择"
                                v-model:value="form.board"
                                style="width: 300px"
                                allowClear
                                :disabled="!form.isSyncJira"
                                @change="handleSelectChange($event, 'board')"
                            >
                                <a-select-option :key="item.name" v-for="item of options.board">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="用户">
                            <div class="caption-font-color">
                                提示：如果没有jira账号，一个系统的所有产品经理可共用一个jira账号创建需求，如有必要可开通jira账号
                            </div>
                            <a-table rowKey="id" :columns="columns" :data-source="detail.pmpSystemManagerDTOs" :pagination="false">
                                <template #jiraAccount="{ record }">
                                    <span v-if="record.jiraAccount">{{ record.jiraAccount }}</span>
                                    <a-tag color="success" v-else>未登录</a-tag>
                                </template>
                            </a-table>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
            <flexbox justify="flex-end" class="btn-group">
                <a-button type="primary" @click="handleSubmit">保存</a-button>
            </flexbox>
        </h-section>
    </div>
</template>

<script lang="ts">
import { message } from 'ant-design-vue';
import store from '@/store';
import { useRouter } from 'vue-router';
import api from '@/api';
import { useMessage } from '@/hooks/common/useMessage';
import { defineComponent, ref, unref, computed } from 'vue';
export default defineComponent({
    props: {
        detail: {
            type: Object,
            default: () => ({})
        }
    },
    setup(props) {
        const { createJiraLogin } = useMessage();
        const router = useRouter();
        const ruleFormRef = ref<any>();
        const form = ref<Recordable>({
            isSyncJira: false,
            url: null,
            projectName: null,
            projectKey: null,
            component: null,
            componentId: null,
            board: null,
            boardId: null
        });
        const options = ref<any>({
            projectName: [], // 项目
            board: [], // 看板
            component: [] // 模块
        });
        const rules = computed(() => {
            const rules = {
                projectKey: [{ required: true, message: '项目关键字不能为空', trigger: 'blur' }],
                board: options.value.board.length ? [{ required: true, message: '看板不能为空', trigger: 'change' }] : []
            };
            return unref(form).isSyncJira ? rules : {};
        });
        const columns = [
            {
                title: '产品经理',
                dataIndex: 'empName',
                width: 200,
                align: 'center'
            },
            {
                title: 'jira帐号',
                key: 'jiraAccount',
                align: 'center',
                slots: { customRender: 'jiraAccount' }
            }
        ];
        const handleSwitchChange = (val) => {
            if (!val) {
                unref(ruleFormRef).clearValidate();
                form.value = {
                    isSyncJira: false,
                    url: null,
                    projectName: null,
                    projectKey: null,
                    component: null,
                    componentId: null,
                    board: null,
                    boardId: null
                };
            } else {
                // 请求项目选项
                if (form.value.isSyncJira && form.value.url) {
                    const target = store.getters.dicOptions.jiraUrl.find((item) => item.dimensionName === form.value.url);
                    if (target) {
                        findByFatherId().then((moule) => {
                            if (moule) {
                                options.value.projectName = [...moule];
                            }
                        });
                    }
                }
            }
        };
        const handleSelectChange = async (val: string, field: string) => {
            // 域名地址
            if (field === 'url') {
                findByFatherId().then((moule) => {
                    if (moule) {
                        options.value.projectName = [...moule];
                        form.value.projectName = '';
                        form.value.projectKey = '';
                    }
                });
            } else {
                let target: any = null;
                if (!unref(options)[field].length) {
                    if (form.value.projectKey) {
                        target = {
                            code: form.value.projectKey,
                            dimensionName: form.value.projectName
                        };
                    } else {
                        return;
                    }
                } else {
                    target = unref(options)[field].find((item) => item.dimensionName === val || item.name === val);
                }
                // 项目关键字
                if (field === 'projectName') {
                    form.value.projectKey = target.code;
                    getComponentAndBoard().then((moule) => {
                        if (moule) {
                            const { board, component } = moule;
                            options.value.board = board || [];
                            options.value.component = component || [];
                            form.value.board = '';
                            form.value.boardId = '';
                            form.value.component = '';
                            form.value.componentId = '';
                        } else {
                            options.value.board = [];
                            options.value.component = [];
                            form.value.board = '';
                            form.value.boardId = '';
                            form.value.component = '';
                            form.value.componentId = '';
                        }
                    });
                }
                if (field === 'component' || field === 'board') {
                    form.value[`${field}Id`] = val ? target.id : '';
                }
            }
        };
        const handleSubmit = () => {
            unref(ruleFormRef)
                .validate()
                .then(() => {
                    handleSave();
                })
                .catch((err) => {
                    console.log(err);
                });
        };
        const handleSave = async () => {
            const query = {
                ...props.detail.pmpJiraDTO,
                ...unref(form),
                isSyncJira: unref(form).isSyncJira ? '1' : '0'
            };
            const { success, errorMsg } = await api.jiraModel.save(query);
            if (success) {
                message.success('操作成功');
                router.push({
                    path: '/setting/system/systemList'
                });
            } else {
                message.error(errorMsg);
            }
        };
        // 请求看板和模块下拉选项
        const getComponentAndBoard = async () => {
            const query = {
                url: form.value.url,
                empId: store.getters.userInfo.employeeDTO.empId,
                projectCode: form.value.projectKey
            };
            try {
                const resArr: any[] = await Promise.all([api.jiraModel.getComponents(query), api.jiraModel.getBoards(query)]);
                const res = resArr.every((item) => item.success);
                if (res) {
                    return {
                        component: resArr[0].moule,
                        board: resArr[1].moule
                    };
                } else {
                    if (resArr.some((item) => item.errorCode === '003')) {
                        createJiraLogin({
                            systemId: props.detail.id,
                            url: form.value.url,
                            onOk() {
                                loginSuccess();
                            }
                        });
                    }
                    return false;
                }
            } catch (err) {
                return false;
            }
        };
        // 请求项目关键字
        const findByFatherId = async () => {
            const target = store.getters.dicOptions.jiraUrl.find((item) => item.dimensionName === form.value.url);
            if (target) {
                const { success, moule } = await api.dicModel.findByFatherId({
                    id: target.id
                });
                if (success) {
                    return moule;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        };
        const loginSuccess = () => {
            getComponentAndBoard().then((moule) => {
                if (moule) {
                    const { board, component } = moule;
                    options.value.board = board || [];
                    options.value.component = component || [];
                    form.value.board = '';
                    form.value.boardId = '';
                    form.value.component = '';
                    form.value.componentId = '';
                } else {
                    options.value.board = [];
                    options.value.component = [];
                    form.value.board = '';
                    form.value.boardId = '';
                    form.value.component = '';
                    form.value.componentId = '';
                }
            });
        };
        const init = async () => {
            const info = props.detail.pmpJiraDTO;
            Object.keys(unref(form)).forEach((key) => {
                if (key === 'isSyncJira') {
                    form.value.isSyncJira = !!+info.isSyncJira;
                } else {
                    form.value[key] = info[key];
                }
            });
            form.value.url = store.getters.dicOptions.jiraUrl[0].dimensionName;
            // 请求项目选项
            if (form.value.isSyncJira && form.value.url) {
                const target = store.getters.dicOptions.jiraUrl.find((item) => item.dimensionName === form.value.url);
                if (target) {
                    findByFatherId().then((moule) => {
                        if (moule) {
                            options.value.projectName = [...moule];
                        }
                    });
                    getComponentAndBoard().then((moule) => {
                        if (moule) {
                            const { board, component } = moule;
                            options.value.board = board || [];
                            options.value.component = component || [];
                        }
                    });
                }
            }
        };
        init();
        return {
            ruleFormRef,
            form,
            options,
            columns,
            rules,
            handleSwitchChange,
            handleSelectChange,
            handleSubmit,
            loginSuccess
        };
    }
});
</script>

<style scoped lang="less">
.cell-item {
    font-size: 14px;
    margin-bottom: 8px;
    &-label {
        color: @caption-font-color;
    }
}
</style>
